package com.ruoyi.door.excel;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.easy.query.api.proxy.client.EasyEntityQuery;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.utils.SysDeptUtil;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.door.controller.admin.adsl.vo.DoorAdslImportVO;
import com.ruoyi.door.domain.DoorAdsl;
import com.ruoyi.door.domain.DoorHouse;
import com.ruoyi.door.domain.DoorLandlord;
import com.ruoyi.system.mapper.SysDeptMapper;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

public class UserDataListener extends AnalysisEventListener<DoorAdslImportVO> {
    private final EasyEntityQuery easyEntityQuery;
    private final SysDeptMapper sysDeptMapper;

    private static final int BATCH_COUNT = 1000;
    List<DoorAdslImportVO> userList = new ArrayList<>();

    public UserDataListener(EasyEntityQuery easyEntityQuery, SysDeptMapper sysDeptMapper) {
        this.easyEntityQuery = easyEntityQuery;
        this.sysDeptMapper = sysDeptMapper;
    }

    @Override
    public void invoke(DoorAdslImportVO user, AnalysisContext context) {
        userList.add(user);
        if (userList.size() >= BATCH_COUNT) {
            saveData();
            userList.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        saveData();
    }

    private void saveData() {
        // 将数据保存到数据库或其他业务处理
        List<SysDept> deptList = sysDeptMapper.selectDeptList(new SysDept());
        List<DoorHouse> houseList = easyEntityQuery.queryable(DoorHouse.class).toList();
        int successCount = 0;
        int failCount = 0;
        StringBuilder failureMsg = new StringBuilder();
        try {

            List<DoorAdsl> insert = new ArrayList<>();
            List<DoorAdsl> update = new ArrayList<>();
            for (int i = 0; i < userList.size(); i++) {
                DoorAdslImportVO adslImportVO = userList.get(i);
                try {
                    // 处理ADSL记录
                    // 验证部门信息并查找对应的房产
                    SysDept root = new SysDept();
                    root.setDeptId(0L);
                    SysDept country = SysDeptUtil.findDeptById(adslImportVO.getCountryName(), 1, root, deptList);
                    if (country == null) {
                        throw new Exception("公司不存在或层级关系错误");
                    }
                    SysDept province = SysDeptUtil.findDeptById(adslImportVO.getProvinceName(), 2, country, deptList);
                    SysDept city = SysDeptUtil.findDeptById(adslImportVO.getCityName(), 3, province, deptList);
                    SysDept district = SysDeptUtil.findDeptById(adslImportVO.getDistrictName(), 4, city, deptList);
                    SysDept street = SysDeptUtil.findDeptById(adslImportVO.getStreetName(), 5, district, deptList);
                    SysDept village = SysDeptUtil.findDeptById(adslImportVO.getVillageName(), 6, street, deptList);

                    if (province == null || city == null || district == null || street == null || village == null) {
                        throw new Exception("部门信息不完整或层级关系错误");
                    }

                    String address = adslImportVO.getAddress();
                    DoorHouse doorHouse = houseList.stream()
                            .filter(x ->
                                x.getProvince().equals(province.getDeptId())&&
                                x.getCity().equals(city.getDeptId())&&
                                x.getDistrict().equals(district.getDeptId())&&
                                x.getStreet().equals(street.getDeptId())&&
                                x.getVillage().equals(village.getDeptId())&&
                                x.getAddress().equals(address)
                            ).findFirst().orElse(null);

                    if (doorHouse == null) {
                        throw new Exception("找不到对应的房产信息");
                    }
                    long doorAdslCount = easyEntityQuery.queryable(DoorAdsl.class)
                            .where(d -> d.houseId().eq(doorHouse.getId())).count();
                    if (doorAdslCount == 0) {
                        // 创建ADSL信息
                        DoorAdsl doorAdsl = new DoorAdsl();
                        BeanUtil.copyProperties(adslImportVO, doorAdsl);
                        doorAdsl.setHouseId(doorHouse.getId());

//                        easyEntityQuery.insertable(doorAdsl).executeRows();
                        insert.add(doorAdsl);
                    } else if (doorAdslCount == 1) {
                        DoorAdsl doorAdsl = easyEntityQuery.queryable(DoorAdsl.class)
                                .where(d -> d.houseId().eq(doorHouse.getId())).firstOrNull();
                        BeanUtil.copyProperties(adslImportVO, doorAdsl);
                        doorAdsl.setHouseId(doorHouse.getId());
                        update.add(doorAdsl);
//                        easyEntityQuery.updatable(doorAdsl).executeRows();
                    } else {
                        continue;
                    }

                    easyEntityQuery.insertable(insert).batch().executeRows();
                    easyEntityQuery.updatable(update).batch().executeRows();
                    insert.clear();
                    update.clear();

                } catch (Exception e) {
                }
            }

        } catch (Exception e) {

        }

    }
}